package org.ouniao.jprint.server.api;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.jms.Queue;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("api/file")
public class FileUploadRestful {

    @Autowired
    private JmsMessagingTemplate jmsTemplate;

    private final String TOKEN_PRE = "jb";

    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, String token) {
        String res = "<h1>{{msg}}</h1>";
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHH"));
        String accessToken = TOKEN_PRE.concat(timeStr);
        if (!token.equals(accessToken)) {
            return res.replace("{{msg}}", "安全码错误");
        }
        if (file.isEmpty()) {
            return res.replace("{{msg}}", "上传失败，请选择文件");
        }
        try {
            Queue queue = new ActiveMQQueue("uploadfile_listenner");
            jmsTemplate.convertAndSend(queue, new Object[]{file.getOriginalFilename(), file.getBytes()});
            return res.replace("{{msg}}", "上传成功");
        } catch (IOException e) {

        }
        return res.replace("{{msg}}", "上传失败");
    }

}
